﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Text;
using System.Web.SessionState;
using MpSoft.Library.BUSS.Products;
using MpSoft.Library.DTO;
using MpSoft.Library.CommonLibrary;
using MpSoft.Library.BUSS.Customers;
using Newtonsoft.Json;

namespace MpSoft.Web.Services
{
    /// <summary>
    /// Summary description for ProductCart
    /// </summary>
    public class ProductCart : IHttpHandler, IRequiresSessionState 
    {
        private string TypeAction = string.Empty;
        private int ProductID, quantity;
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/html";
            LoadValue(context);
            ProcessAction(context);
        }

        private void ProcessAction(HttpContext context)
        {
            switch (TypeAction)
            {
                case "removecart":
                    RemoveCart(context);
                    break;
                case "changequantity":
                    ChangeQuantity(context);
                    break;
                case"ping":
                    PingWebsite(context);
                    break;
                case "addcart":
                    AddCart(context);
                    break;
            }
        }

        private void PingWebsite(HttpContext context)
        {
            context.Response.Write("Ping...!");
        }
        //Xóa giỏ hàng
        private void RemoveCart(HttpContext context)
        {
            context.Session["ListCart"] = null;
            context.Response.Write(1);
        }
        // Thay đổi số lượng giỏ hàng
        private void ChangeQuantity(HttpContext context)
        {
            var listcartSession = context.Session["ListCart"];
            if (listcartSession != null)
            {
                var listcart = (List<Cart>)listcartSession;
                int index = OrderBUSS.CheckedProductID(listcart, ProductID);
                if (index >= 0)
                {
                    listcart[index].Quantily = quantity;
                    context.Session["ListCart"] = listcart;
                    var totalOrder = OrderBUSS.GetTotalOrder(listcart);
                    var total = listcart[index].Total;
                    var result = new { TotalOrder = totalOrder > 0 ? totalOrder + " VNĐ" : "Liên hệ", Total = total > 0 ? total + " VNĐ" : "Liên hệ" };
                    context.Response.Write(JsonConvert.SerializeObject(result));
                }
            }
        }

        // add product to cart
        private void AddCart(HttpContext context)
        {
            var listcartSession = context.Session["ListCart"];
            var objProduct = ProductBUSS.Product_ByID(ProductID);
            if (objProduct != null)
            {
                var temp = Template.GetTemplate(context.Server.MapPath(@"\Templates\PopupCart.html"), "");
                Cart objCart = new Cart();
                objCart.ProductID = objProduct.ProductID;
                objCart.Images = objProduct.Images;
                objCart.FormatUrl = objProduct.FormatUrl;
                objCart.Price = objProduct.PriceNew > 0 ? objProduct.PriceNew : objProduct.Price;
                objCart.ProductName = objProduct.ProductName;
                objCart.Quantily = quantity;
                
                if (listcartSession != null)
                {
                    var listcart = (List<Cart>)listcartSession;
                    var ixProduct = OrderBUSS.CheckedProductID(listcart, objProduct.ProductID);
                    if (ixProduct >= 0)
                        listcart[ixProduct].Quantily = listcart[ixProduct].Quantily + quantity;
                    else
                        listcart.Add(objCart);
                    context.Session["ListCart"] = listcart;
                    var total = OrderBUSS.GetTotalOrder(listcart);
                    HttpContext.Current.Response.Write(string.Format(temp, ShowProductSelect(objProduct, quantity), (total > 0 ? Filter.Money(total.ToString()) + " VNĐ" : "Liên hệ"), listcart.Count, ProductOrther(objProduct.CategoryID)));
                }
                else
                {
                    List<Cart> listcart = new List<Cart>();
                    listcart.Add(objCart);
                    context.Session["ListCart"] = listcart;
                    var total = OrderBUSS.GetTotalOrder(listcart);
                    HttpContext.Current.Response.Write(string.Format(temp, ShowProductSelect(objProduct, quantity), (total > 0 ? Filter.Money(total.ToString()) + " VNĐ" : "Liên hệ"), listcart.Count, ProductOrther(objProduct.CategoryID)));
                }
            }
        }
        // Hiển thị sản phẩm lựa chọn đặt mua
        private string ShowProductSelect(Product obj, int quantity)
        {
            StringBuilder sb = new StringBuilder();
            var img = "";
            if (obj.Images.Contains("@"))
                img = obj.Images.Split('@')[0];
            else
                img = obj.Images.Split(',')[0];
            var url = string.Format(obj.FormatUrl, obj.ProductID);
            sb.Append("<a class='img' href='" + url + "'><img src='" + img + "' /></a>");
            sb.Append("<a class='name' href='" + url + "'>Samsung Galaxy Grand 2 G7102</a>");
            if (obj.Price < 1)
                sb.Append("<span>Giá: Liên hệ</span>");
            else
                sb.Append("<span>Giá: " + (obj.PriceNew > 0 ? Filter.Money(obj.PriceNew.ToString()) : Filter.Money(obj.Price.ToString())) + " VNĐ</span>");
            sb.Append("<span>Số lượng: " + quantity + "</span>");
            return sb.ToString();
        }
        //Hiển thị những sản phảm khác ở sản phẩm đặt mua
        private string ProductOrther(int CategoryID)
        {
            var list = ProductBUSS.Product_List(CategoryID, 1, 1, false, false, false, false, 5);
            if (list != null)
            {
                StringBuilder sb = new StringBuilder();
                sb.Append("<ul class='listprod'>");
                string img = string.Empty;
                var url = "";
                foreach (var obj in list)
                {
                    sb.Append("<li>");
                    if (obj.Images.Contains("@"))
                        img = obj.Images.Split('@')[0];
                    else
                        img = obj.Images.Split(',')[0];
                    url = string.Format(obj.FormatUrl, obj.ProductID);
                    sb.Append("<a class='img' href='" + url + "'><img src='" + img + "' /></a>");
                    sb.Append("<a class='name' href='" + url + "'>" + obj.ProductName + "</a>");
                    if (obj.Price < 1)
                        sb.Append("<p>Giá: Liên hệ</p>");
                    else
                        sb.Append("<p>Giá: " + (obj.PriceNew > 0 ? Filter.Money(obj.PriceNew.ToString()) : Filter.Money(obj.Price.ToString())) + " VNĐ</p>");
                    sb.Append("</li>");
                }
                sb.Append("</ul>");
                return sb.ToString();
            }
            return "";
        }
        //tham số yêu cầu
        private void LoadValue(HttpContext context)
        {
            if (context.Request.QueryString["type"] != null)
                TypeAction = context.Request.QueryString["type"].ToString();
            if (context.Request.QueryString["prodid"] != null)
                int.TryParse(context.Request.QueryString["prodid"].ToString(), out ProductID);
            if (context.Request.QueryString["quantity"] != null)
                int.TryParse(context.Request.QueryString["quantity"].ToString(), out quantity);
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}